<?php

namespace App\Services;

use App\Exceptions\InternalException;
use App\Exceptions\InvalidRequestException;
use App\Models\LaborExit;
use Illuminate\Support\Facades\Log;

class LaborExitService
{
    public function get($title)
    {
        $sql = LaborExit::when($title, function ($query, $title) {
            return $query->where(function ($query) use ($title) {
                $query->where('name', 'like', '%' . $title . '%');
            });
        });
        return $sql;
    }

    public function insert($input)
    {
        //判断是否存在
        $is = LaborExit::where('labor_id', $input['labor_id'])->first();
        if ($is) {
            throw new InvalidRequestException('该人员已退场');
        }

        if ($input['exit_date']) {
            $input['exit_date'] = Date("Y-m-d", $input['exit_date'] / 1000);
        }
        $res = [];
        foreach ($input as $k => $v) {
            if ($v) {
                $res[$k] = $v;
            }
        }

        try {
            $data = LaborExit::create($res);
            if ($data) {
                return $data->id;
            }
        } catch (\Throwable $th) {
            Log::info(json_encode($th));
            throw new InternalException('提交失败');
        }
    }

    public function update($input)
    {
        if ($input['exit_date']) {
            $input['exit_date'] = Date("Y-m-d", $input['exit_date'] / 1000);
        }
        $res = [];
        foreach ($input as $k => $v) {
            if ($v) {
                $res[$k] = $v;
            }
        }
        unset($res['id']);
        try {
            $data = LaborExit::where('id', $input['id'])->update($res);
            if ($data) {
                return $input['id'];
            }
        } catch (\Throwable $th) {
            Log::info(json_encode($th));
            throw new InternalException('提交失败');
        }
    }
}
